package com.apusic.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apusic.common.Constants;
import com.apusic.entity.TSystemUser;
import com.apusic.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class LoginController {
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@Autowired
	private SystemUserService systemUserService;
	

	@RequestMapping(value = "/login")
	public String login(HttpServletRequest request,
			HttpServletResponse response) {
		TSystemUser user = (TSystemUser)request.getSession().getAttribute(Constants.Session_key);
		try {
			if(null!=user){
				//response.sendRedirect("/loginning");
				return "redirect:/loginning";
			}else{
				return "login";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "/loginIndex")
	public String loginIndex(HttpServletRequest request,
			HttpServletResponse response) {
		String userName = (String)request.getParameter("userAccount");
		String userPwd = (String)request.getParameter("userPassword");
		TSystemUser user = new TSystemUser(userName,userPwd);
		List<TSystemUser> userList = systemUserService.getSystemUser(user);
		try {
			if(userList!=null&& userList.size()>0){
				TSystemUser seesionUser= userList.get(0);
				request.getSession().setAttribute(Constants.Session_key,seesionUser);
				request.getSession().setAttribute("aaa","bbb");
				//response.sendRedirect("/loginning");
				return "redirect:/loginning";
			}else{
				//response.sendRedirect("/login");
				return "redirect:/login";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "/loginning")
	public String showIndex(HttpServletRequest request,
			HttpServletResponse response) {
		TSystemUser user = (TSystemUser)request.getSession().getAttribute(Constants.Session_key);
		try {
			if(null==user){
				//response.sendRedirect("/login");
				return "redirect:/login";
			}else{
				return "index";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		request.getSession().invalidate();
		try {
			response.sendRedirect("/login");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
